--[[
    设置 cookie ，有 cookie 则通过请求，没有 cookie 则进行限流
    具体限流方法由链中下一条规则处理，如果链中没有下一条规则，那么
    相当于限行。

    第一次进入因为没有 cookie 则肯定会被限流，限流后会写 cookie 
    第二次进入就不会限了。

    Author: mahaixing@gmail.com
    License: MIT
]]

local assert = assert
local util = require("utils")
local cookie = require("resty.cookie")

local _M = require("limiters.limiter"):new()

function _M:process_config()
    self.cookie_key = assert(self.conf.cookie_key
                                "Please set cookie_key in cookie section!")
    self.cookie_value = assert(self.conf.cookie_value, 
                                "Please set cookie_value in cookie section!")
    self.cookie_path = assert(self.conf.cookie_path,
                                "Please set cookie_path in cookie section!")
    self.cookie_domain = assert(self.conf.cookie_domain,
                                "Please set cookie_domain in cookie section!")
end

function _M:execute()
    if not cookie then return false end

    local field, err = cookie:get(self.cookie_key)
    if field == self.cookie_value then
        return false, false
    else
        cookie:set({
            key = self.cookie_key, 
            value = self.cookie_value,
            path = self.cookie_path,
            domain = self.cookie_domain
        });
        return true, true
    end
end

return _M